const express = require('express');
const router = express.Router();
const externalApi = require('../services/externalApi');
const { validateRequest } = require('../middleware/validation');
const logger = require('../utils/logger');

/**
 * @route GET /api/external/stock/:symbol
 * @desc 获取股票信息
 * @access Public
 */
router.get('/stock/:symbol', async (req, res) => {
  try {
    const { symbol } = req.params;
    const { source = 'default' } = req.query;
    
    logger.info(`获取股票信息: ${symbol}`, { source });
    
    // 这里可以配置不同的数据源
    let stockData;
    switch (source) {
      case 'yahoo':
        stockData = await externalApi.get(`https://query1.finance.yahoo.com/v8/finance/chart/${symbol}`);
        break;
      case 'alpha':
        stockData = await externalApi.get(`https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${symbol}&apikey=${process.env.ALPHA_VANTAGE_API_KEY}`);
        break;
      default:
        // 模拟股票数据
        stockData = {
          symbol: symbol.toUpperCase(),
          price: (Math.random() * 1000 + 10).toFixed(2),
          change: (Math.random() * 20 - 10).toFixed(2),
          changePercent: (Math.random() * 10 - 5).toFixed(2),
          volume: Math.floor(Math.random() * 1000000),
          timestamp: new Date().toISOString()
        };
    }
    
    res.json({
      success: true,
      data: stockData,
      source,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('获取股票信息失败', { error: error.message, symbol: req.params.symbol });
    res.status(500).json({
      success: false,
      error: '获取股票信息失败',
      message: error.message
    });
  }
});

/**
 * @route POST /api/external/stock/batch
 * @desc 批量获取股票信息
 * @access Public
 */
router.post('/stock/batch', validateRequest({
  symbols: 'array|required',
  source: 'string|optional'
}), async (req, res) => {
  try {
    const { symbols, source = 'default' } = req.body;
    
    logger.info(`批量获取股票信息`, { count: symbols.length, source });
    
    const requests = symbols.map(symbol => ({
      method: 'GET',
      url: `/api/external/stock/${symbol}?source=${source}`,
      config: {}
    }));
    
    const results = await externalApi.batch(requests);
    
    res.json({
      success: true,
      data: results,
      count: symbols.length,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('批量获取股票信息失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '批量获取股票信息失败',
      message: error.message
    });
  }
});

/**
 * @route GET /api/external/market/overview
 * @desc 获取市场概览
 * @access Public
 */
router.get('/market/overview', async (req, res) => {
  try {
    logger.info('获取市场概览');
    
    // 模拟市场数据
    const marketData = {
      indices: [
        { name: '上证指数', symbol: 'SH000001', price: '3200.50', change: '+15.20', changePercent: '+0.48%' },
        { name: '深证成指', symbol: 'SZ399001', price: '12800.30', change: '+45.80', changePercent: '+0.36%' },
        { name: '创业板指', symbol: 'SZ399006', price: '2650.20', change: '+12.50', changePercent: '+0.47%' }
      ],
      sectors: [
        { name: '科技', change: '+2.1%', leading: 'AI概念股' },
        { name: '新能源', change: '+1.8%', leading: '光伏板块' },
        { name: '医药', change: '-0.5%', leading: '创新药' }
      ],
      timestamp: new Date().toISOString()
    };
    
    res.json({
      success: true,
      data: marketData,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('获取市场概览失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '获取市场概览失败',
      message: error.message
    });
  }
});

/**
 * @route POST /api/external/news/search
 * @desc 搜索财经新闻
 * @access Public
 */
router.post('/news/search', validateRequest({
  keywords: 'string|required',
  limit: 'number|optional'
}), async (req, res) => {
  try {
    const { keywords, limit = 10 } = req.body;
    
    logger.info(`搜索财经新闻`, { keywords, limit });
    
    // 模拟新闻搜索结果
    const newsData = {
      query: keywords,
      total: Math.floor(Math.random() * 100) + 10,
      results: Array.from({ length: Math.min(limit, 10) }, (_, i) => ({
        id: `news_${Date.now()}_${i}`,
        title: `关于"${keywords}"的财经新闻标题 ${i + 1}`,
        summary: `这是关于"${keywords}"的新闻摘要，包含了相关的财经信息和市场分析...`,
        source: `财经媒体${i + 1}`,
        publishTime: new Date(Date.now() - Math.random() * 86400000).toISOString(),
        url: `https://example.com/news/${i + 1}`,
        relevance: (Math.random() * 0.5 + 0.5).toFixed(2)
      })),
      timestamp: new Date().toISOString()
    };
    
    res.json({
      success: true,
      data: newsData,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('搜索财经新闻失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '搜索财经新闻失败',
      message: error.message
    });
  }
});

/**
 * @route GET /api/external/economic/indicators
 * @desc 获取经济指标
 * @access Public
 */
router.get('/economic/indicators', async (req, res) => {
  try {
    logger.info('获取经济指标');
    
    // 模拟经济指标数据
    const indicators = {
      gdp: { value: '121.02', unit: '万亿元', growth: '+3.0%', period: '2023年Q4' },
      cpi: { value: '102.5', unit: '指数', growth: '+2.5%', period: '2024年1月' },
      pmi: { value: '50.1', unit: '指数', growth: '+0.1', period: '2024年1月' },
      unemployment: { value: '5.1', unit: '%', growth: '-0.1%', period: '2024年1月' },
      timestamp: new Date().toISOString()
    };
    
    res.json({
      success: true,
      data: indicators,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('获取经济指标失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '获取经济指标失败',
      message: error.message
    });
  }
});

module.exports = router;
